package br.com.upcoder.fguard.client.presenter;

import java.util.ArrayList;
import java.util.List;

import br.com.upcoder.fguard.client.presenter.event.AddDebtEvent;
import br.com.upcoder.fguard.client.shared.Budget;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

public class ListBudgetsPresenter implements Presenter {

	HandlerManager eventBus;
	Display display;
	List<Budget> budgets;

	public ListBudgetsPresenter(HandlerManager eventBus, Display display) {
		this.eventBus = eventBus;
		this.display = display;
	}

	@Override
	public void go(HasWidgets container) {
		container.clear();
		container.add(display.asWidget());
		init();
	}

	private void init() {
		budgets = retrieveAllBudgets();
		displayBudgets();
		bind();
	}

	private List<Budget> retrieveAllBudgets() {
		List<Budget> budgets = new ArrayList<Budget>();
		Budget b01 = new Budget(333, "B00000000001", 1.0, 0.5);
		Budget b02 = new Budget(555, "B00000000002", 1.0, 0.5);
		Budget b03 = new Budget(888, "B00000000003", 1.0, 0.5);
		Budget b04 = new Budget(999, "B00000000004", 1.0, 0.5);
		Budget b05 = new Budget(100, "B00000000005", 1.0, 0.5);
		Budget b06 = new Budget(111, "B00000000006", 1.0, 0.5);
		Budget b07 = new Budget(222, "B00000000007", 1.0, 0.5);
		Budget b08 = new Budget(444, "B00000000008", 1.0, 0.5);
		Budget b09 = new Budget(666, "B00000000009", 1.0, 0.5);
		Budget b10 = new Budget(101, "B00000000010", 1.0, 0.5);

		budgets.add(b01);
		budgets.add(b02);
		budgets.add(b03);
		budgets.add(b04);
		budgets.add(b05);
		budgets.add(b06);
		budgets.add(b07);
		budgets.add(b08);
		budgets.add(b09);
		budgets.add(b10);

		return budgets;

	}

	private void displayBudgets() {
		String[][] data = new String[budgets.size()][4];
		for (int i = 0; i < budgets.size(); i++) {
			data[i][0] = String.valueOf(budgets.get(i).getCode());
			data[i][1] = String.valueOf(budgets.get(i).getName());
			data[i][2] = String.valueOf(budgets.get(i).getTotalAmount());
			data[i][3] = String.valueOf(budgets.get(i).getAvailableAmount());
		}
		display.setData(data);
	}

	private void bind() {
		List<HasClickHandlers> buttons = display.getAddDebtButtons();
		for (int i = 0; i < buttons.size(); ++i) {
			createAddDebtBtnHandler(buttons.get(i), i);
		}
	}

	private void createAddDebtBtnHandler(HasClickHandlers button, final int i) {
		button.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				eventBus.fireEvent(new AddDebtEvent(budgets.get(i)));
			}
		});
	}

	public interface Display {
		Widget asWidget();

		List<HasClickHandlers> getAddDebtButtons();

		void setData(String[][] data);
	}

}
